package com.xinenhua.businessserver.login;

import android.app.Dialog;
import android.graphics.Color;
import android.text.InputType;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oasis.oasislib.base.BaseFragmentActivity;
import com.oasis.oasislib.base.HttpCallBack;
import com.oasis.oasislib.utils.DialogUtils;
import com.oasis.oasislib.utils.LogUtil;
import com.oasis.oasislib.utils.ToastUtils;
import com.oasis.oasislib.view.PhoneCode;
import com.xinenhua.businessserver.Const;
import com.xinenhua.businessserver.MainActivity;
import com.xinenhua.businessserver.R;
import com.xinenhua.businessserver.http.BaseHttp;
import com.xinenhua.businessserver.login.pojo.User;


import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 设置密码
 */
@ContentView(R.layout.setpsw)
public class SetPsw extends BaseFragmentActivity {

    @ViewInject(R.id.ppppppp)
    EditText editTextpsw;

    PhoneCode pc_1;

    @ViewInject(R.id.textView4)
    TextView yanzhengtextView4;

    private ToggleButton tb;


    //手机号
    String phonenum;

    //密码
    String psw;

    //验证码
    String sign;

    @ViewInject(R.id.imageButton)
    RelativeLayout imageButton;

    Dialog dialog;

    //这个字段区分  是注册设置密码  还是修改密码！！！！！！
    boolean setpsw  = false;

    //项目id
    String project_id ;

    //项目
    String position ;

    @Override
    protected void start() {
        super.start();
        mTitleBar.setCenterTitle("注册");
        mTitleBar.setBackViewVisiable(true);
        mTitleBar.setVisibility(View.GONE);

        StatusBarCompat.setStatusBarColor(this, Color.WHITE);
        actionBar.hide();

        phonenum = getIntent().getStringExtra("phone");
        sign = getIntent().getStringExtra("sign");
        String setpswString = getIntent().getStringExtra("setpsw");


        position = getIntent().getStringExtra("position");
        project_id = getIntent().getStringExtra("project_id");

        LogUtil.e(TAG,"getphone num---"+phonenum);
        LogUtil.e(TAG,"getsign num---"+sign);
        LogUtil.e(TAG,"setpswString ---" + setpswString);
        if("1".equals(setpswString)){
            setpsw = true;
        }

        tb = (ToggleButton)findViewById(R.id.toggleButton2);
        tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    editTextpsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    LogUtil.e(TAG,"on");
                }else {
                    editTextpsw.setInputType(InputType.TYPE_CLASS_TEXT);
                    LogUtil.e(TAG,"off");
                }
            }
        });


        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //LogUtil.e(TAG,);

                if(setpsw){
                    // 修改密码
                    setpsw1();
                }else {
                    //注册 设置密码
                    setpsw();
                }
            }
        });


    }


    //注册设置密码
    private void setpsw(){

        psw =  editTextpsw.getText().toString();
        if(StringUtils.isBlank(psw)){
            ToastUtils.shortToast(context,"请输入密码");
            return;
        }
        if(psw.length()<6||psw.length()>20){
            ToastUtils.shortToast(context,"请输入6-20位字符的密码");
            return;
        }


        dialog = DialogUtils.createLoadingDialog(context);
        dialog.show();

        HashMap<String,String> map = new HashMap<>() ;
        map.put("phone",phonenum);
        map.put("password",psw);
        map.put("sign",sign);
        map.put("project_id",project_id);
        map.put("position",position);

        Call call = BaseHttp.getCallWithUrlAndData(Const.register,map);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("Fail");
                showMsg("发生错误");
                dialog.dismiss();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String rr = new String(response.body().string());
                System.out.println(rr);
                int result = BaseHttp.preResult(rr);
                if(result==BaseHttp.DATA_OK){
                    String s = BaseHttp.getJsonDataAsString(rr);

                    Gson gson = new Gson();
                    Type listType = new TypeToken<User>(){}.getType();
                    User user = gson.fromJson(s, listType);

                    //存储用户信息
//                    SPUtils spUtils = SPUtils.getInstance();
//                    spUtils.put("user",s);

                    //跳到首页
                    ActivityUtils.startActivity(Login.class);

                    System.out.println(s);
                    showMsg("注册成功 请等待审核");

                }else {
                    System.out.println(BaseHttp.getJsonMsg(rr));
                    showMsg(BaseHttp.getJsonMsg(rr));
                }
                dialog.dismiss();
            }
        });
    }


    //找回密码  修改密码
    private void setpsw1(){

        psw =  editTextpsw.getText().toString();
        if(StringUtils.isBlank(psw)){
            ToastUtils.shortToast(context,"请输入密码");
            return;
        }

        dialog = DialogUtils.createLoadingDialog(context);
        dialog.show();

        RequestParams requestParams = new RequestParams(Const.changepsw) ;
        requestParams.setConnectTimeout(10*1000);
        requestParams.addBodyParameter("access_token", Const.access_token());
        requestParams.addBodyParameter("phone", phonenum);
        requestParams.addBodyParameter("password", psw);
        requestParams.addBodyParameter("sign", sign);
        LogUtil.e(TAG,"phone--"+phonenum);
        LogUtil.e(TAG,"password---"+psw);
        LogUtil.e(TAG,"sign---"+sign);
        loadData(requestParams, new HttpCallBack() {
            @Override
            public void onSuccess(String result) {
                LogUtil.e(TAG,"changepsw--"+result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int code = jsonObject.getInt("code") ;
                    if(code==0){
                        // servernum = jsonObject.getJSONObject("data").getString("sign") ;
                        ToastUtils.shortToast(context,"修改成功");

                        String s = BaseHttp.getJsonDataAsString(result);
                        Gson gson = new Gson();
                        Type listType = new TypeToken<User>(){}.getType();
                        //得到了用户信息
                        User user = gson.fromJson(s, listType);

                        //存储用户信息
                        SPUtils spUtils = SPUtils.getInstance();
                        spUtils.put("user",s);

                        ActivityUtils.startActivity(MainActivity.class);
                    }else {
                        ToastUtils.shortToast(context,jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                dialog.dismiss();
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.shortToast(context,Const.errortip);
            }
        });
    }




    @Event(value = R.id.imageView8, type = View.OnClickListener.class)
    private void finish(View view) {
        finish();
    }
}
